# -*- coding: UTF-8 -*-
"""
DTU 控制指令分发模块（mod_dispatch.py）
用于处理 MQTT 控制指令，如 OTA、重启、配置更新等
"""

import utime as time
import config
import mod_system
import mod_mqtt
import uos
import service_data
import mod_time


def _process_config_action(message):
    """处理配置相关的业务逻辑，返回结果字典"""
    try:
        action = message.get("action")

        if action == "get_config":
            key = message.get("key")
            if key:
                try:
                    value = config.get_config(key)
                    return {"status": "success", "key": key, "value": value}
                except Exception as e:
                    return {
                        "status": "error",
                        "message": "Error getting config {}: {}".format(key, str(e)),
                    }
            else:
                return {"status": "error", "message": "Missing key parameter"}

        elif action == "set_config":
            key = message.get("key")
            value = message.get("value")
            if key is not None and value is not None:
                try:
                    if config.set_config(key, value):
                        return {
                            "status": "success",
                            "key": key,
                            "value": value,
                            "message": "Config updated",
                        }
                    else:
                        return {"status": "error", "message": "Failed to set config"}
                except Exception as e:
                    return {
                        "status": "error",
                        "message": "Error setting config {}: {}".format(key, str(e)),
                    }
            else:
                return {"status": "error", "message": "Missing key or value parameter"}

        elif action == "update_config":
            updated_count = 0
            errors = []

            for key, value in message.items():
                if key != "action":
                    try:
                        if config.set_config(key, value):
                            updated_count += 1
                        else:
                            errors.append("Failed to set {}".format(key))
                    except Exception as e:
                        errors.append("Error setting {}: {}".format(key, str(e)))

            if errors:
                return {
                    "status": "partial_success",
                    "updated_count": updated_count,
                    "errors": errors,
                    "message": "Some configs updated with errors",
                }
            else:
                return {
                    "status": "success",
                    "updated_count": updated_count,
                    "message": "All configs updated successfully",
                }

        elif action == "list_config":
            supported_keys = config.get_supported_config_keys()
            return {
                "status": "success",
                "data": supported_keys,
                "usage": "Use 'get_config', 'set_config', 'update_config', or 'get_all_config' action",
                "examples": [
                    {"action": "get_config", "key": "device.device_sn"},
                    {
                        "action": "set_config",
                        "key": "device.device_sn",
                        "value": "new_value",
                    },
                    {
                        "action": "update_config",
                        "device.device_sn": "new_sn",
                        "mqtt.port": 1883,
                    },
                    {"action": "get_all_config"},
                ],
            }

        elif action == "get_all_config":
            supported_keys = config.get_supported_config_keys()
            all_config_data = {}
            for key in supported_keys:
                try:
                    value = config.get_config(key)
                    all_config_data[key] = value
                except Exception as e:
                    all_config_data[key] = "Error: {}".format(str(e))

            return {
                "status": "success",
                "action": "get_all_config",
                "data": all_config_data,
            }
        elif action == "flash_config":
            result = config.flash_config()
            print("flash_config result:{}".format(result))
            return {
                "status": "success",
                "action": "flash_config",
                "data": result,
            }
        elif action == "time":

            return {
                "status": "success",
                "action": "time",
                "current_time_beijing": mod_time.get_current_beijing_time(),
                "current_time_utc": mod_time.get_current_time_utc(),
                "timestamp": time.time(),
                "time_synced": mod_time.is_time_synced(),
            }
        elif action == "flash_format":
            formatflash = uos.formatflash()
            return {
                "status": "success",
                "action": "formatflash",
                "message": "formatflash result:{}".format(formatflash),
            }
        elif action == "flash_info":
            flash_info = uos.flashinfo()
            return {
                "status": "success",
                "action": "flash_info",
                "time": mod_time.get_current_beijing_time(),
                "data": flash_info,
                "message": "flash_info result:{}".format(flash_info),
            }
        # version
        elif action == "version":
            return {
                "status": "success",
                "action": "version",
                "time": mod_time.get_current_beijing_time(),
                "data": config.get_config("system.version"),
                "message": "version result:{}".format(
                    config.get_config("system.version")
                ),
            }
        elif action == "system_info":
            system_info = service_data.runtime_data_collector.collect_system_data()
            return {
                "status": "success",
                "action": "system_info",
                "time": mod_time.get_current_beijing_time(),
                "data": system_info,
                "message": "get system info succes",
            }

        elif action == "data_info":
            flash_data_count = service_data.runtime_data_collector.flash_data_count()
            return {
                "status": "success",
                "action": "data_info",
                "time": mod_time.get_current_beijing_time(),
                "data": flash_data_count,
                "message": "get data info succes",
            }

        elif action == "data_clear":
            service_data.runtime_data_collector.clear_all_data()
            flash_data_count = service_data.runtime_data_collector.flash_data_count()
            return {
                "status": "success",
                "action": "data_clear",
                "time": mod_time.get_current_beijing_time(),
                "data": flash_data_count,
                "message": "clear all data",
            }

        else:
            return {
                "status": "error",
                "message": "Unsupported config action: {}".format(action),
            }

    except Exception as e:
        return {
            "status": "error",
            "message": "Config processing error: {}".format(str(e)),
        }


def handle_action(message):
    """
    处理控制类指令（如 MQTT control topic 下发的消息）
    参数：
        message (dict): 从 MQTT 解析的 JSON 字典
    """
    try:
        print("[DISPATCH] Received action message:", message)

        action = message.get("action")
        params = message.get("params", {})

        if action == "reboot":
            print("[DISPATCH] exe reboot...")
            mod_mqtt.publish_status({"status": "rebooting"})
            time.sleep(3)
            mod_system.restart()

        elif action == "ota":
            print("[DISPATCH]exe OTA now")
            mod_mqtt.publish_status({"status": "ota_started"})
            import mod_ota

            mod_ota.init()
            mod_ota.manual_trigger()
            # 可自行实现 OTA 下载+升级逻辑
            # from mod_ota import upgrade_firmware
            # upgrade_firmware(params.get("url"))
        # time_sync

        elif action == "time_sync":
            print("[DISPATCH] time_sync now...")
            import mod_time

            mod_time.sync_time()
            mod_mqtt.publish_status(
                {"time_async_at: ": mod_time.get_current_beijing_time()}
            )

        elif action == "ping":
            mod_mqtt.publish_status({"status": "pong"})
            print("[DISPATCH] get ping, reply pong ")

        else:
            print("[DISPATCH] Processing config action: {}".format(action))
            result = _process_config_action(message)
            mod_mqtt.publish_status(result)
            print(
                "[DISPATCH] Config action {} ,completed with result: {}".format(
                    action, result
                )
            )

    except Exception as e:
        print("[DISPATCH] error", e)
        mod_mqtt.publish_status(
            {"status": "error", "message": "Dispatch error: {}".format(str(e))}
        )


def handle_action_for_ttl(message):
    """处理TTL控制指令（不发布MQTT消息，直接返回结果）"""
    try:
        print("[DISPATCH] Received TTL action message:", message)
        action = message.get("action")
        result = _process_config_action(message)
        print(
            "[DISPATCH] TTL action {} completed with status: {}".format(
                action, result.get("status")
            )
        )
        return result

    except Exception as e:
        error_result = {
            "status": "error",
            "message": "Dispatch error: {}".format(str(e)),
        }
        print("[DISPATCH] TTL error", e)
        return error_result
